using B.S.NewMedical.Api.Write.Application.Command.ContentManagement.Patient;
using B.S.NewMedical.Api.Write.Common;
using B.S.NewMedical.Domain.Hospital;
using B.S.NewMedical.Infrastructure.Interface;
using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.NewMedical.Api.Write.Application.Handler.ContentManagement.Patient
{
    /// <summary>
    /// 删除患者命令处理器
    /// </summary>
    public class DeletePatientCommandHandler : IRequestHandler<DeletePatientCommand, BatchDeleteResult>
    {
        private readonly IBaseRepository<PatientModel> _patientRepository;

        public DeletePatientCommandHandler(IBaseRepository<PatientModel> patientRepository)
        {
            _patientRepository = patientRepository ?? throw new ArgumentNullException(nameof(patientRepository));
        }

        /// <summary>
        /// 处理批量删除患者命令
        /// </summary>
        /// <param name="request">批量删除患者命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>批量删除结果</returns>
        public async Task<BatchDeleteResult> Handle(DeletePatientCommand request, CancellationToken cancellationToken)
        {
            var result = new BatchDeleteResult();
            var successIds = new List<int>();
            var failedIds = new List<int>();

            foreach (var id in request.Ids)
            {
                try
                {
                    // 查找要删除的患者
                    var patient = await _patientRepository.GetValue(id);
                    if (patient != null && !patient.IsDeleted)
                    {
                        // 这里可以添加业务逻辑检查，比如：
                        // - 检查是否有未完成的挂号记录
                        // - 检查是否有未完成的就诊记录
                        // - 检查是否有未缴费的订单等
                        
                        // 示例：检查是否有关联的就诊记录（如果需要的话）
                        // var hasActiveVisits = await CheckActiveVisits(id);
                        // if (hasActiveVisits)
                        // {
                        //     failedIds.Add(id);
                        //     result.FailCount++;
                        //     continue;
                        // }

                        // 软删除：设置删除状态和更新时间
                        patient.IsDeleted = true;
                        patient.UpdateTime = DateTime.Now;
                        patient.UpdatePeople = request.UpdatePeople;

                        await _patientRepository.UpdateAsync(patient);
                        successIds.Add(id);
                        result.SuccessCount++;
                    }
                    else
                    {
                        failedIds.Add(id);
                        result.FailCount++;
                    }
                }
                catch (Exception)
                {
                    failedIds.Add(id);
                    result.FailCount++;
                }
            }

            result.FailedIds = failedIds;
            result.Success = result.FailCount == 0;

            if (result.Success)
            {
                result.Message = $"成功删除 {result.SuccessCount} 个患者";
            }
            else
            {
                if (result.SuccessCount > 0)
                {
                    result.Message = $"成功删除 {result.SuccessCount} 个患者，失败 {result.FailCount} 个患者";
                }
                else
                {
                    result.Message = $"删除失败，{result.FailCount} 个患者不存在或已被删除";
                }
            }

            return result;
        }

        // 示例：检查患者是否有活跃的就诊记录（根据实际业务需求实现）
        // private async Task<bool> CheckActiveVisits(int patientId)
        // {
        //     // 这里可以注入其他仓储来检查关联记录
        //     // 比如检查VisitRecordModel表中是否有该患者的未完成记录
        //     return false;
        // }
    }
}